<?php
/**
 * Created by PhpStorm.
 * User: jingshou
 * Date: 2017/9/10
 * Time: 15:42
 */

namespace app\admin\model;

use think\Db;
use think\Model;
use think\Session;

class Type extends Model
{
    protected $table = 'tp_type';

    public function subModel()
    {
        return $this->hasMany('Type','pId');
    }

    public static function typeList($condition, $order = 'id desc')
    {
        $query = Type::find();

        if (!empty($condition['id'])) {
            $query->where(['id' => $condition['id']]);
        }
        if (!empty($condition['typeName'])) {
            $query->where('typeName', 'like', '%' . $condition['typeName'] . '%');
        }
        if (isset($condition['pId'])) {
            $query->where(['pId' => $condition['pId']]);
        }

        $list = $query->where(['type' => $condition['type']])->order($order)->paginate(20, false, [
            'query' => $condition,
        ]);
        return $list;
    }

    public static function typeAdd(array $data)
    {
        if (empty($data)) {
            return resError('参数为空');
        }

        Db::startTrans();
        try {
            $model = new Type();
            $model->data($data);
            $model->language = Session::get('language');
            $model->created = time();
            $model->creater = 'admin';
            $model->state = !empty($data['state']) && $data['state'] == 'on' ? 0 : 1;
            if ($model->save() == 0) {
                return resError($model->getError());
            }
            Db::commit();
            return resData('添加成功', \url('type_list'));
        } catch (\Exception $e) {
            Db::rollback();
            return resError($e->getMessage());
        }
    }

    public static function typeUpdate(array $data)
    {
        $model = Type::get($data['id']);
        $model->data($data);
        $model->state = !empty($data['state']) && $data['state'] == 'on' ? 0 : 1;
        if ($model->save() == 0) {
            return resError('更新失败');
        }
        return resData('更新成功', \url('type_list'), $model->toArray());
    }

    public static function typeDel($id)
    {
        $model = Type::get($id);
        if ($model->delete() > 0) {
            return resData('删除成功');
        } else {
            return resError('删除失败');
        }
    }
}